module.exports = app => {
  const express = require('express');
  const router = express.Router();
  const Category = require('../../models/Category');
  const assert = require('http-assert')
  /**新增分类 */
  router.post('/categories', async (req, res) => {
    const model = await Category.create(req.body);
    res.send(model);
  })
  /**分类列表 */
  router.get('/categories/list', async (req, res) => {
    const item = await Category.find().populate('parent').limit(10);
    res.send(item);
  })
  /**点击编辑 */
  router.get('/categories/edit', async (req, res) => {
    const item = await Category.findById(req.query.id);
    res.send(item);
  })
  /**编辑完保持 */
  router.post('/categories/save', async (req, res) => {
    const item = await Category.findByIdAndUpdate(req.body._id, req.body);
    res.send(item);
  })
  /**删除 */
  router.post('/categories/remove', async (req, res) => {
    console.log(req.body);
    const item = await Category.findByIdAndDelete(req.body.id, req.body, (err) => {
      res.send({
        suess: "删除成功"
      });
    });
  })
  /**上传图片 */
  const multer = require('multer');
  const upload = multer({ dest: __dirname + '/../../uploads' });
  router.post('/upload', upload.single('file'), async (req, res) => {
    const file = req.file;
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  })

  const AdminUser = require('../../models/AdminUser');
  /**用户注册 */
  router.post('/register', async (req, res) => {
    console.log(req.body);
    const item = await AdminUser.create(req.body)
    res.send(item)
  })
  /**用户登录 */
  router.post('/login', async (req, res) => {
    const { username, password } = req.body; //相当于 const username=req.body.username
    // 1、根据用户查找账号是否存在 结构赋值的写法
    const user = await AdminUser.findOne({ username }).select('+password')//相当于 username:username 
    assert(user, 422, "用户不存在")
    // if (!user) {
    //   return res.status(422).send({
    //     messages: "用户不存在"
    //   })
    // }
    //2、判断密码是否正确
    const isValid = require('bcryptjs').compareSync(password, user.password)//返回true或false判断是否正确  明文  密文
    if (!isValid) {
      return res.status(422).send({
        messages: "密码错误"
      })
    }
    //3、返回token
    const jwt = require('jsonwebtoken');
    /**生成token */
    const token = jwt.sign({ _id: user._id }, app.get('secret'))
    res.send({
      token: token,
      username: username
    })
  })
  app.use('/admin/api', router)
}